<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      th:replace="~{layout/base :: html(content=~{::content}, extraScripts=~{::extraScripts}, extraHead=~{::extraHead})}">
<head>
    <th:block th:fragment="extraHead">
        <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    </th:block>
</head>
<body>
<th:block th:fragment="content">
    <div class="container mt-4">
        <h2 class="mb-4">球墨铸铁炉料管理数据库</h2>

        <!-- 搜索表单 -->
        <div class="card mb-4">
            <div class="card-body">
                <form id="searchForm" class="row g-2 align-items-center">
                    <div class="col-auto">
                        <input type="text" name="title" class="form-control" placeholder="标题关键字"
                               th:value="${searchParams?.title}">
                    </div>
                    <div class="col-auto">
                        <input type="number" name="minPrice" class="form-control" placeholder="最低价格"
                               th:value="${searchParams?.minPrice}">
                    </div>
                    <div class="col-auto">
                        <input type="number" name="maxPrice" class="form-control" placeholder="最高价格"
                               th:value="${searchParams?.maxPrice}">
                    </div>
                    <div class="col-auto">
                        <select name="district" class="form-control" id="districtSelect">
                            <option value="">所有区域</option>
                        </select>
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-primary">搜索</button>
                        <button type="button" class="btn btn-secondary" onclick="resetSearch()">重置</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 添加按钮 -->
        <div class="mb-3">
            <a th:href="@{/listings/create}" class="btn btn-success">添加</a>
        </div>



        <!-- 列表内容 -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="thead-light">
                        <tr>
                            <th>车型</th>
                            <th>区域</th>
                            <th>价格</th>
                            <th>类型</th>
                            <th>司机名称</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="listingsTableBody">
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <div id="paginationContainer" class="d-flex justify-content-between align-items-center mt-3">
                </div>
            </div>
        </div>
    </div>
</th:block>

<th:block th:fragment="extraScripts">
    <script th:inline="javascript">
        // 确保Chart.js加载完成
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof Chart === 'undefined') {
                console.error('Chart.js not loaded!');
                return;
            }
            console.log('Chart.js loaded successfully');
        });

        // 定义一个列表页面的管理对象
        const listingManager = {
            currentPage: 1,

            // 初始化函数
            initialize: function() {
                console.log('Initializing listings page');
                try {
                    // 加载区域数据
                    this.loadDistricts();
                    // 加载列表数据
                    this.loadData(1);

                    // 监听表单提交
                    const form = document.getElementById('searchForm');
                    if (!form) {
                        console.error('Search form not found');
                        return;
                    }

                    form.addEventListener('submit', (e) => {
                        e.preventDefault();
                        this.loadData(1);
                    });
                } catch (error) {
                    console.error('Error during initialization:', error);
                }
            },

            // 加载区域数据
            loadDistricts: function() {
                console.log('Loading districts');
                fetch('/listings/districts')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(districts => {
                        console.log('Received districts:', districts);
                        const select = document.getElementById('districtSelect');
                        if (!select) {
                            console.error('District select element not found');
                            return;
                        }

                        select.innerHTML = '<option value="">所有区域</option>';
                        districts.forEach(district => {
                            const option = document.createElement('option');
                            option.value = district;
                            option.textContent = district;
                            select.appendChild(option);
                        });
                    })
                    .catch(error => {
                        console.error('Error loading districts:', error);
                    });
            },

            // 加载数据
            loadData: function(page) {
                this.currentPage = page;
                const formData = new FormData(document.getElementById('searchForm'));
                const params = new URLSearchParams(formData);
                params.set('current', page);

                console.log('Loading data with params:', params.toString());

                fetch(`/listings/data?${params.toString()}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('Received data:', data);
                        if (!data.listings) {
                            console.error('No listings data in response');
                            return;
                        }
                        this.updateTable(data.listings);
                        this.updatePagination(data);
                    })
                    .catch(error => {
                        console.error('Error loading data:', error);
                        alert('加载数据失败，请刷新页面重试');
                    });
            },

            // 更新表格内容
            updateTable: function(listings) {
                console.log('Updating table with listings:', listings);
                const tbody = document.getElementById('listingsTableBody');
                if (!tbody) {
                    console.error('Table body element not found');
                    return;
                }

                tbody.innerHTML = '';

                if (!listings.length) {
                    const tr = document.createElement('tr');
                    tr.innerHTML = '<td colspan="7" class="text-center">暂无数据</td>';
                    tbody.appendChild(tr);
                    return;
                }

                listings.forEach(listing => {
                    try {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                                <td>${listing.title || ''}</td>
                                <td>${listing.location || ''}</td>
                                <td>${listing.price || ''}</td>
                                <td>${listing.roomType || ''}</td>
                                <td>${listing.hostName}</td>
                                <td>
                                    <span class="badge ${listing.status == 1 ? 'bg-success' : 'bg-secondary'} text-white"
                                          style="font-size: 14px; padding: 5px 10px;">
                                        ${listing.status == 1 ? '上架' : '下架'}
                                    </span>
                                </td>
                                <td>
                                    <a href="/listings/edit/${listing.listingId}" class="btn btn-sm btn-primary">编辑</a>
                                    <a href="/listings/delete/${listing.listingId}"
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('确定要删除这条记录吗？')">删除</a>
                                </td>
                            `;
                        tbody.appendChild(tr);
                    } catch (error) {
                        console.error('Error creating table row:', error, listing);
                    }
                });
            },

            // 更新分页
            updatePagination: function(data) {
                console.log('Updating pagination with data:', data);
                const container = document.getElementById('paginationContainer');
                if (!container) {
                    console.error('Pagination container not found');
                    return;
                }

                if (!data.pages || data.pages <= 1) {
                    container.innerHTML = '';
                    return;
                }

                let paginationHtml = `
                        <div class="text-muted">
                            共 ${data.total} 条记录，
                            当前第 ${data.current}/${data.pages} 页
                        </div>
                        <nav>
                            <ul class="pagination mb-0">
                    `;

                // 上一页
                paginationHtml += `
                        <li class="page-item ${data.current == 1 ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0)" onclick="listingManager.loadData(${data.current - 1})">&laquo;</a>
                        </li>
                    `;

                // 首页
                if (data.current > 3) {
                    paginationHtml += `
                            <li class="page-item">
                                <a class="page-link" href="javascript:void(0)" onclick="listingManager.loadData(1)">1</a>
                            </li>
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                        `;
                }

                // 页码
                for (let i = Math.max(1, data.current - 2); i <= Math.min(data.pages, data.current + 2); i++) {
                    paginationHtml += `
                            <li class="page-item ${i == data.current ? 'active' : ''}">
                                <a class="page-link" href="javascript:void(0)" onclick="listingManager.loadData(${i})">${i}</a>
                            </li>
                        `;
                }

                // 末页
                if (data.current < data.pages - 2) {
                    paginationHtml += `
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="javascript:void(0)" onclick="listingManager.loadData(${data.pages})">${data.pages}</a>
                            </li>
                        `;
                }

                // 下一页
                paginationHtml += `
                        <li class="page-item ${data.current == data.pages ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0)" onclick="listingManager.loadData(${data.current + 1})">&raquo;</a>
                        </li>
                    `;

                paginationHtml += `
                            </ul>
                        </nav>
                    `;

                container.innerHTML = paginationHtml;
            },

            // 重置搜索
            resetSearch: function() {
                document.getElementById('searchForm').reset();
                this.loadData(1);
            },

            // 调试数据
            debugData: function() {
                const formData = new FormData(document.getElementById('searchForm'));
                const params = new URLSearchParams(formData);
                params.set('current', this.currentPage);

                fetch(`/listings/data?${params.toString()}`)
                    .then(response => response.json())
                    .then(data => {
                        console.log('Debug - Full response:', data);
                        console.log('Debug - Listings:', data.listings);
                        console.log('Debug - Pagination:', {
                            current: data.current,
                            pages: data.pages,
                            total: data.total,
                            size: data.size
                        });
                        alert('请查看控制台输出');
                    })
                    .catch(error => {
                        console.error('Debug - Error:', error);
                        alert('调试出错，请查看控制台');
                    });
            }
        };

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => listingManager.initialize());

        // 为了支持AJAX加载，暴露初始化函数
        window.initializeListings = () => listingManager.initialize();

        // 暴露重置搜索函数
        window.resetSearch = () => listingManager.resetSearch();

        // 暴露调试函数
        window.debugData = () => listingManager.debugData();

        // 显示导入模态框
        function showImportModal() {
            const modal = new bootstrap.Modal(document.getElementById('importModal'));
            modal.show();
            // 清空之前的结果
            document.getElementById('importResult').style.display = 'none';
            document.getElementById('importForm').reset();
        }

        // 导入Excel
        function importExcel() {
            const fileInput = document.getElementById('excelFile');
            const resultDiv = document.getElementById('importResult');

            if (!fileInput.files || fileInput.files.length === 0) {
                showImportResult('请选择要上传的文件', false);
                return;
            }

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            // 显示加载状态
            const importButton = document.querySelector('#importModal .btn-primary');
            const originalText = importButton.textContent;
            importButton.disabled = true;
            importButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 导入中...';

            fetch('/listings/import', {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('导入响应数据:', data); // 添加日志
                    if (data.success) {
                        showImportResult(data.message, true, data.errors);
                        // 重新加载数据
                        listingManager.loadData(1);
                        // 2秒后关闭模态框
                        setTimeout(() => {
                            const modal = bootstrap.Modal.getInstance(document.getElementById('importModal'));
                            if (modal) {
                                modal.hide();
                            }
                        }, 2000);
                    } else {
                        showImportResult(data.message, false, data.errors);
                    }
                })
                .catch(error => {
                    console.error('导入失败:', error);
                    showImportResult('导入失败，请稍后重试', false);
                })
                .finally(() => {
                    // 恢复按钮状态
                    importButton.disabled = false;
                    importButton.textContent = originalText;
                });
        }

        // 显示导入结果
        function showImportResult(message, success, errors) {
            console.log('显示导入结果:', { message, success, errors }); // 添加日志
            const resultDiv = document.getElementById('importResult');
            resultDiv.className = 'alert ' + (success ? 'alert-success' : 'alert-danger');
            let html = message;

            if (errors && errors.length > 0) {
                html += '<ul class="mb-0 mt-2">';
                errors.forEach(error => {
                    html += `<li>${error}</li>`;
                });
                html += '</ul>';
            }

            resultDiv.innerHTML = html;
            resultDiv.style.display = 'block';
        }

        let currentTaskId = null;
        let statusCheckInterval = null;

        // 显示清洗模态框
        function showCleanModal() {
            const modal = new bootstrap.Modal(document.getElementById('cleanModal'));
            modal.show();
            resetCleanUI();
        }

        // 重置清洗UI
        function resetCleanUI() {
            document.getElementById('cleanProgress').style.display = 'none';
            document.getElementById('cleanRecords').style.display = 'none';
            document.getElementById('startCleanBtn').style.display = 'block';
            document.getElementById('stopCleanBtn').style.display = 'none';
            document.getElementById('cleanStatus').className = 'alert';
            document.getElementById('cleanStatus').innerHTML = '';
            if (statusCheckInterval) {
                clearInterval(statusCheckInterval);
                statusCheckInterval = null;
            }

            // 安全地销毁图表
            const chartCanvas = document.getElementById('statsChart');
            if (chartCanvas) {
                const chartInstance = Chart.getChart(chartCanvas);
                if (chartInstance) {
                    chartInstance.destroy();
                }
            }
        }

        // 开始清洗
        function startClean() {
            document.getElementById('cleanProgress').style.display = 'block';
            document.getElementById('startCleanBtn').style.display = 'none';
            document.getElementById('stopCleanBtn').style.display = 'block';
            document.getElementById('cleanStatus').className = 'alert alert-info';
            document.getElementById('cleanStatus').innerHTML = '正在启动清洗任务...';

            fetch('/api/data-clean/start', {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentTaskId = data.taskId;
                        document.getElementById('cleanStatus').innerHTML = '任务已启动，正在处理...';
                        startStatusCheck();
                    } else {
                        showCleanError(data.message);
                    }
                })
                .catch(error => {
                    console.error('启动清洗任务失败:', error);
                    showCleanError('启动任务失败，请稍后重试');
                });
        }

        // 停止清洗
        function stopClean() {
            if (!currentTaskId) return;

            fetch(`/api/data-clean/stop/${currentTaskId}`, {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showCleanMessage('任务已停止', 'warning');
                    } else {
                        showCleanError(data.message);
                    }
                })
                .catch(error => {
                    console.error('停止任务失败:', error);
                    showCleanError('停止任务失败，请稍后重试');
                });
        }

        // 开始检查状态
        function startStatusCheck() {
            if (statusCheckInterval) {
                clearInterval(statusCheckInterval);
            }

            let failedAttempts = 0;
            const MAX_FAILED_ATTEMPTS = 3;

            statusCheckInterval = setInterval(() => {
                if (!currentTaskId) {
                    clearInterval(statusCheckInterval);
                    return;
                }

                fetch(`/api/data-clean/status/${currentTaskId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.data) {
                            failedAttempts = 0; // 重置失败计数
                            updateCleanProgress(data.data);

                            // 如果任务完成或失败，停止检查
                            if (['COMPLETED', 'FAILED', 'STOPPED'].includes(data.data.status)) {
                                clearInterval(statusCheckInterval);
                                statusCheckInterval = null;
                                document.getElementById('stopCleanBtn').style.display = 'none';

                                // 如果成功完成，延迟关闭模态框并刷新数据
                                if (data.data.status === 'COMPLETED') {
                                    setTimeout(() => {
                                        listingManager.loadData(listingManager.currentPage);
                                    }, 1000);
                                }
                            }
                        }
                    })
                    .catch(error => {
                        console.error('获取任务状态失败:', error);
                        failedAttempts++;

                        // 如果连续失败超过最大次数，停止检查
                        if (failedAttempts >= MAX_FAILED_ATTEMPTS) {
                            clearInterval(statusCheckInterval);
                            statusCheckInterval = null;
                            showCleanError('获取任务状态失败，请刷新页面重试');
                        }
                    });
            }, 2000); // 每2秒检查一次状态
        }

        // 更新清洗进度
        function updateCleanProgress(task) {
            const progressBar = document.querySelector('#cleanProgress .progress-bar');
            const statusDiv = document.getElementById('cleanStatus');

            if (task.total > 0) {
                const percentage = (task.processed / task.total) * 100;
                progressBar.style.width = percentage + '%';
                progressBar.setAttribute('aria-valuenow', percentage);
            }

            let statusClass = 'alert-info';
            if (task.status === 'COMPLETED') {
                statusClass = 'alert-success';
                // 任务完成后加载清洗记录
                loadCleanRecords(task.taskId);
            } else if (task.status === 'FAILED') {
                statusClass = 'alert-danger';
            } else if (task.status === 'STOPPED') {
                statusClass = 'alert-warning';
            }

            statusDiv.className = `alert ${statusClass}`;
            let message = task.message || '';
            if (task.total > 0) {
                message += `<br>成功：${task.succeeded}，失败：${task.failed}`;
            }
            statusDiv.innerHTML = message;
        }

        // 加载清洗记录
        function loadCleanRecords(taskId) {
            fetch(`/api/data-clean/records/${taskId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('cleanRecords').style.display = 'block';
                        if (data.stats && data.stats.length > 0) {
                            updateStats(data.stats);
                        }
                        if (data.records && data.records.length > 0) {
                            updateRecordsTable(data.records);
                        } else {
                            document.getElementById('recordsTableBody').innerHTML =
                                '<tr><td colspan="5" class="text-center">暂无清洗记录</td></tr>';
                        }
                    } else {
                        showCleanError(data.message);
                    }
                })
                .catch(error => {
                    console.error('获取清洗记录失败:', error);
                    showCleanError('获取清洗记录失败，请稍后重试');
                });
        }

        // 更新统计图表
        function updateStats(stats) {
            const chartData = {
                labels: [],
                values: []
            };

            const typeNames = {
                'TITLE': '标题',
                'PRICE': '价格',
                'AREA': '面积',
                'LOCATION': '位置',
                'DESCRIPTION': '描述'
            };

            stats.forEach(item => {
                chartData.labels.push(typeNames[item.clean_type] || item.clean_type);
                chartData.values.push(item.count);
            });

            const ctx = document.getElementById('statsChart');

            // 安全地销毁旧图表
            const existingChart = Chart.getChart(ctx);
            if (existingChart) {
                existingChart.destroy();
            }

            // 创建新图表
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        label: '清洗数量',
                        data: chartData.values,
                        backgroundColor: 'rgba(54, 162, 235, 0.2)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        title: {
                            display: true,
                            text: '数据清洗统计'
                        }
                    }
                }
            });
        }

        // 更新记录表格
        function updateRecordsTable(records) {
            const tbody = document.getElementById('recordsTableBody');
            tbody.innerHTML = '';

            const typeNames = {
                'TITLE': '标题',
                'PRICE': '价格',
                'AREA': '面积',
                'LOCATION': '位置',
                'DESCRIPTION': '描述'
            };

            records.forEach(record => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                        <td>${typeNames[record.cleanType] || record.cleanType}</td>
                        <td>${record.oldValue}</td>
                        <td>${record.newValue}</td>
                        <td>${record.remark}</td>
                        <td>${formatDateTime(record.createdAt)}</td>
                    `;
                tbody.appendChild(tr);
            });
        }

        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '';
            const date = new Date(dateTimeStr);
            return date.toLocaleString();
        }

        // 显示清洗错误
        function showCleanError(message) {
            const statusDiv = document.getElementById('cleanStatus');
            statusDiv.className = 'alert alert-danger';
            statusDiv.innerHTML = message;
            document.getElementById('stopCleanBtn').style.display = 'none';
            document.getElementById('startCleanBtn').style.display = 'block';
        }

        // 显示清洗消息
        function showCleanMessage(message, type = 'info') {
            const statusDiv = document.getElementById('cleanStatus');
            statusDiv.className = `alert alert-${type}`;
            statusDiv.innerHTML = message;
        }
    </script>
</th:block>
</body>
</html> 